from fastapi import APIRouter
from fastapi import HTTPException,  Request
from schema.item import Item


store_router = APIRouter()


@store_router.post("/history")
async def put_item(request: Request, item: Item):
    store = request.app.state.store
    namespace = item.namespace
    key = item.key
    history_item = await store.aget(("user", namespace), key)
    if history_item is None:
        await store.aput(("user", namespace), item.key, item.value)
    else:
        history = item.value["history"][0]
        history_item.value["history"].insert(0, history)
        await store.aput(("user", namespace), item.key, history_item.value)
    return {"status": "ok"}

@store_router.get("/get/{namespace}/{key}", response_model=Item)
async def get_item(request: Request, namespace: str, key: str):
    store = request.app.state.store
    value = await store.aget(("user", namespace), key)
    print(value)
    if value is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return value


@store_router.delete("/delete/{namespace}/{key}")
async def delete_item(request: Request, namespace: str, key: str):
    store = request.app.state.store
    await store.adelete(("user", namespace), key)
    return {"status": "deleted"}